package main

import (
	"fmt"
	"io"
	"log"
	"os"

	"golang.org/x/net/context"

	"gitee.com/wang1974/go-grpcservice/pb"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials"
	"google.golang.org/grpc/metadata"
)

const host = "localhost:8081"

func main() {
	creds, err := credentials.NewClientTLSFromFile("cert.pem", "")
	if err != nil {
		log.Fatal(err.Error())
	}
	// 客户端option
	options := []grpc.DialOption{grpc.WithTransportCredentials(creds)}
	// 拨号 与服务器建立连接
	conn, err := grpc.Dial(host, options...)
	if err != nil {
		log.Fatal(err.Error())
	}
	defer conn.Close()

	client := pb.NewEmployeeServiceClient(conn)
	// fmt.Println(client)
	GetByNo(client)
	// getAll(client)
	// addPhoto(client)
}

func GetByNo(client pb.EmployeeServiceClient) {
	res, err := client.GetByNo(context.Background(), &pb.GetByNoRequset{No: 1994})
	if err != nil {
		log.Fatal(err.Error())
	}
	fmt.Println(res.Employee)
}

func getAll(client pb.EmployeeServiceClient) {
	stream, err := client.GetAll(context.Background(), &pb.GetAllRequest{})
	if err != nil {
		log.Fatal(err.Error())
	}
	for {
		res, err := stream.Recv()
		if err == io.EOF {
			log.Fatal("EOF: ", err.Error())
			break
		}
		if err != nil {
			log.Fatal(err.Error())
		}
		fmt.Println(res.Employee)
	}
}

func addPhoto(client pb.EmployeeServiceClient) {
	imgfile, err := os.Open("1.png")
	if err != nil {
		log.Fatal(err.Error())
	}
	defer imgfile.Close()

	md := metadata.New(map[string]string{"no": "2004"})

	context := context.Background()
	context = metadata.NewOutgoingContext(context, md)

	stream, err := client.AddPhoto(context)
	if err != nil {
		log.Fatal(err.Error())
	}
	for {
		chunk := make([]byte, 128*1024)
		chunksize, err := imgfile.Read(chunk)
		if err == io.EOF {
			break
		}
		if err != nil {
			log.Fatal(err.Error())
		}
		if chunksize < len(chunk) {
			chunk = chunk[:chunksize]
		}
		stream.Send(&pb.AddPhotoRequest{Data: chunk})
	}
	res, err := stream.CloseAndRecv()
	if err != nil {
		log.Fatal(err.Error())
	}
	fmt.Println(res.IsOk)
}

func saveAll(client pb.EmployeeServiceClient) {
	var employees = []pb.Employee{
		{
			Id:        3,
			No:        1995,
			FirstName: "zxf",
			LastName:  "wqrr",
		},
		{
			Id:        4,
			No:        1998,
			FirstName: "zsk",
			LastName:  "fww",
		},
	}
	stream, err := client.SaveAll(context.Background())
	if err != nil {
		log.Fatal(err.Error())
	}
	finishChannel := make(chan struct{})
	go func() {
		for {
			res, err := stream.Recv()
			if err == io.EOF {
				finishChannel <- struct{}{}
				break
			}
			if err != nil {
				log.Fatal(err.Error())
			}
			fmt.Println(res.Employee)
		}
	}()
	for _, e := range employees {
		err := stream.Send(&pb.EmployeeRequest{Employee: &e})
		if err != nil {
			log.Fatal(err.Error())
		}
	}
	stream.CloseSend()
	<-finishChannel
}
